package cn.stylefeng.mferp.socketio.remind;

//import cn.stylefeng.mferp.modular.system.model.User;
//import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.corundumstudio.socketio.SocketIOClient;
//import com.corundumstudio.socketio.SocketIOServer;
//import com.liyisoft.pay4another.channel.constant.Constant;
//import com.liyisoft.pay4another.channel.entity.*;
//import com.liyisoft.pay4another.channel.entity.enums.OrderStatusEnum;
//import com.liyisoft.pay4another.channel.service.IPayRoomInfoService;
//import com.liyisoft.pay4another.channel.service.ISysUserService;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yzr
 */
@Service
public class RemindServiceImpl implements RemindService {
    /*private final Logger logger = LoggerFactory.getLogger(this.getClass());

    *//**
     * 用来存已连接的客户端
      *//*
    public static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();

    *//**
     * 角色
     *//*
    public static Map<String, Long> roleIdMap = new ConcurrentHashMap<>();

    @Autowired
    private SocketIOServer socketIOServer;

    *//**
     * Spring IoC容器创建之后，在加载SocketIOServiceImpl Bean之后启动
     * @throws Exception
     *//*
    @PostConstruct
    private void autoStartup() throws Exception {
        start();
    }

    *//**
     * Spring IoC容器在销毁SocketIOServiceImpl Bean之前关闭,避免重启项目服务端口占用问题
     * @throws Exception
     *//*
    @PreDestroy
    private void autoStop() throws Exception {
        stop();
    }

    @Override
    public void start() {
        // 监听客户端连接
        socketIOServer.addConnectListener(client -> {
            User sysUser = getUserByClient(client);
            RemindMessage remindMessage = new RemindMessage();
            if (sysUser != null) {
                String username = sysUser.getUsername();
                logger.info("有新客户端连接username:{}", username);
                SocketIOClient oldClient = clientMap.get(username);
                // 已登录，提示并断开连接
                if (null == oldClient) {
                    clientMap.put(username, client);
                    roleIdMap.put(username, sysUser.getRoleId());
                } else {
                    clientMap.remove(username);
                    roleIdMap.remove(username);
                    oldClient.disconnect();
                    clientMap.put(username, client);
                    roleIdMap.put(username, sysUser.getRoleId());
                }
            } else {
                // 用户不存在，返回错误
                client.disconnect();
            }
        });

        // 监听客户端断开连接
        socketIOServer.addDisconnectListener(client -> {
            String username = getParamsByClient(client);
            if (StringUtils.isNotBlank(username)) {

                // 查询用户是否存在
                QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("username", username);
                SysUser sysUser = iSysUserService.getOne(queryWrapper);

                if(sysUser != null) {
                    // 断开连接
                    clientMap.remove(username);
                    roleIdMap.remove(username);
                    client.disconnect();
                }
            }
            logger.info("一条客户端连接中断");
        });

        // 处理自定义的事件，与连接监听类似
        // 此示例中测试的json收发 所以接收参数为JSONObject 如果是字符类型可以用String.class或者Object.class
        socketIOServer.addEventListener("ServerReceive", JSONObject.class, (client, data, ackSender) -> {
            // TODO do something
            JSONObject jsonObject = data;
            String uid = getParamsByClient(client);
            if (uid != null) {
                logger.info("接收到SID:{}发来的消息:{}", uid, jsonObject.toJSONString());
            }
        });
        socketIOServer.start();
        logger.info("socket.io初始化服务完成");
    }

    @Override
    public void stop() {
        if (socketIOServer != null) {
            socketIOServer.stop();
            socketIOServer = null;
        }
        logger.info("socket.io服务已关闭");
    }

    *//**
     * 断开连接
     *
     * @param username
     *//*
    @Override
    public void disconnect(String username) {

    }

    *//**
     * 推送信息
     *
     * @param remindMessage
     *//*
    @Override
    public void pushMessageToUser(RemindMessage remindMessage) {
        String username = remindMessage.getUsername();
        SocketIOClient client = clientMap.get(username);
        if (client != null) {
            client.sendEvent("client_receive", remindMessage);
        }
    }

    *//**
     * 消息推送
     *
     * @param username
     * @param content
     * @param event
     *//*
    @Override
    public void pushMessageToUser(String username, String content, String event) {
        RemindMessage remindMessage = new RemindMessage();
        remindMessage.setUsername(username);
        remindMessage.setContent(content);
        SocketIOClient client = clientMap.get(username);
        if (client != null) {
            client.sendEvent(event, remindMessage);
        }
    }

    *//**
     * 充值订单审核信息 推送给商户端
     *
     * @param info 充值订单
     *//*
    *//*@Override
    public void pushChargeMessageToMch(PayMchChargeInfo info) {
        if(info == null) {
            return;
        }
        String username = info.getMchid().toString();
        RemindMessage remindMessage = new RemindMessage();
        remindMessage.setUsername(username);
        StringBuilder content = new StringBuilder();
        content.append("当前您有一条充值审核消息：");
        content.append("充值订单").append(info.getTransactionId()).append(",");
        if(Constant.AUDIT_STATUS_SUCCESS.equals(info.getAuditStatue())) {
            content.append("审核成功，请查收");
        } else if(Constant.AUDIT_STATUS_FAILED.equals(info.getAuditStatue())) {
            content.append("审核失败，请查收");
        }
        remindMessage.setContent(content.toString());
        pushMessageToUser(remindMessage);
    }*//*

    *//**
     * 此方法为获取client连接中的参数，可根据需求更改
     * @param client
     * @return
     *//*
    private String getParamsByClient(SocketIOClient client) {
        // 从请求的连接中拿出参数（这里的sid必须是唯一标识）
        Map<String, List<String>> params = client.getHandshakeData().getUrlParams();
        List<String> list = params.get("username");
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    private User getUserByClient(SocketIOClient client) {
        // 从请求的连接中拿出参数（这里的sid必须是唯一标识）
        Map<String, List<String>> params = client.getHandshakeData().getUrlParams();
        List<String> list = params.get("token");
        if (list != null && list.size() > 0) {
            String token = list.get(0);

        }
        return null;
    }*/
}